<?php
namespace Plu\qdh\Models\App;

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Resultset\Simple as Resultset;

class Order extends Model
{
    private $_connection;

    // CREATE TABLE `orders` (
    //     `id` int(11) NOT NULL AUTO_INCREMENT,
    //     `travelDay` int(11) NOT NULL COMMENT '游玩日期',
    //     `orderId` int(11) DEFAULT NULL,
    //     `productNo` int(11) NOT NULL COMMENT '产品号',
    //     `orderAccount` int(11) DEFAULT NULL COMMENT '下单账户',
    //     `nickName` varchar(45) DEFAULT NULL COMMENT '下单人微信号',
    //     `num` int(11) NOT NULL COMMENT '预定数量',
    //     `linkMan` varchar(45) DEFAULT NULL COMMENT '联系人姓名',
    //     `linkPhone` int(11) NOT NULL COMMENT '联系人手机号',
    //     `status` tinyint(1) NOT NULL COMMENT '订单状态（我方）',
    //     `orderState` tinyint(1) NOT NULL COMMENT '订单状态（第三方）',
    //     `price` decimal(8,2) NOT NULL  COMMENT '销售价',
    //     `createTime` int(11) NOT NULL  COMMENT '下单时间',
    //     `payTime` int(11) DEFAULT NULL COMMENT '支付时间',
    //     `updateTime` int(11) NOT NULL  COMMENT '更新时间',
    //     PRIMARY KEY (`id`)
    //   ) ENGINE=InnoDB DEFAULT CHARSET=utf8

    public function initialize() {
        $this->setConnectionService('db.qdh');
        $this->allowEmptyStringValues([]);
    }

	public function getSource() {
		return "orders";
    }

    static public function getItemById($orderId) {
        $item = self::findFirst([
            'conditions' => 'id = :id:',
            'bind' => [
                'id' => $orderId
            ]
        ]);
        return $item;
    }


    static public function gerItems($limit, $offset, $search = []) {

        $conditions = [];
        // 搜索全部
        if ($search['status'] == 888) {
            unset($search['status']);
        }
        if (empty($search)) {
            $search['status'] = 1;
        }

        foreach($search as $key => $value) {
            $conditions[] = " $key = $value ";
        }
 
        $condition = join(" AND ", $conditions);

        $count = self::count($condition);
        $items = self::find([
            'conditions' => $condition,
            'limit'  => $limit,
            'offset' => $offset,
            'order'  => 'createTime desc'
        ]);

        if ($items) {
            $items = $items->toArray();
            return [$count, $items];
        }

        return [0, []];

    }


    static public function getItemByOrderId($orderId) {
        $item = self::findFirst([
            'conditions' => 'orderId = :orderId:',
            'bind' => [
                'orderId' => $orderId
            ]
        ]);
        return $item;
    }

    static public function getItemsByUid($userId, $limit, $offset, $status) {
	
     	if ($status == 1) {
            $status = " 0, 1, 2";
        } else {
            $status = "9,3,4,5,7,8,6";
        }
        $where = [
            'conditions' => " orderAccount = :uid: AND status in ($status)  ",
            'bind' => [
                'uid' => $userId
            ]
        ];

        $count = self::count($where);
        $where['limit']  = $limit;
        $where['offset'] = $offset;
        $where['order']  = " createTime desc ";

        $items = self::find($where);

        if ($items) {
            $items = $items->toArray();
            return [$count, $items];
        }
        return [0, []];
    }


    public function excuteTask() {
        $now = time();
        $bind = [];
        $setStatus  = \OrderConst::ORDER_STATUS['expire'];
        $needStatus = \OrderConst::ORDER_STATUS['wating'];
        $connection = $this->getReadConnection();
        $sql   = "UPDATE orders a SET a.status = $setStatus WHERE a.status = $needStatus AND a.payLimitTime < $now";
        $c     = $connection->convertBoundParams($sql, $bind);
        $phql  = $c['sql'];
        $_bind = $c['params'];
        return $this->getReadConnection()->query($phql, $_bind);
    }

    // 获取每日收益
    public function multDaliyProfitsReport($custId, $startTime, $endTime) {

        $bind = [];

        $sql = "SELECT
        sum(num)   as totalNum,
        status     as orderStatus,
        updateTime as updateTime, 
        custId     as custId,
        sum(spreadPrize)     as totalspreadPrize,
        sum(totalPrice)      as totalPrice,
        sum(SettlementPrice) as totalSettlementPrice
        FROM  Plu\qdh\Models\App\Order
        WHERE updateTime >= $startTime AND updateTime < $endTime
        AND   isPay  = 1
        AND   custId = $custId    
        ";

        $modelsManager = $this->getDI()->get('modelsManager');

        $items = $modelsManager->executeQuery($sql);

        return $items;
    }

    // 获取每日退款
    public function multDalitRefindReport($custId, $startTime, $endTime) {

        $bind = [];
        $sql = "SELECT
        sum(num)   as redoundTotalNum,
        updateTime as refoundUpdateTime, 
        custId     as refoundCustId,
        sum(spreadPrize)     as refoundTotalSpreadPrize,
        sum(totalPrice)      as refoundTotalPrice,
        sum(SettlementPrice) as refoundtotalSettlementPrice
        FROM  Plu\qdh\Models\App\Order 
        WHERE updateTime >= $startTime AND updateTime < $endTime
        AND   isRefound = 1
        AND   custId = $custId    
        ";

        $modelsManager = $this->getDI()->get('modelsManager');

        $items = $modelsManager->executeQuery($sql);

        return $items;

    }






}
